#include "StdAfx.h"

#define _USE_MATH_DEFINES
#include <math.h>
#include <cmath>

#include "../ColorUtils/Color.h"
#include "../ColorUtils/Image.h"

#include "FlatCylinder.h"

#include "TexturedCylinder.h"

TexturedCylinder::TexturedCylinder(const Ray& ray, double length, double radius, const Image_ptr textureImage) : 
	FlatCylinder(ray, length, radius, Point(0, 0, 0))
	, _image(textureImage)
	, _r((ray.D.X != 0 || ray.D.Y != 0) ? Direction(ray.D.Y, -ray.D.X, 0): Direction(1, 0, 0))
{}

void TexturedCylinder::ColorAtIntersection(SecondIntersectionResult& result, const Point& point, const Ray&)
{
	Point cylinderCenterPoint = _startPoint + _direction * result.ExtraInfoDouble;
	double y = acos(_r.ScalarProduct(point - cylinderCenterPoint) * _radiusInv);
	if (abs(_direction.Z) < 0.95)
	{
		if (cylinderCenterPoint.Z < point.Z)
			y = -y;
	}
	else
		if (cylinderCenterPoint.Y < point.Y)
			y = -y;


	y /= (2 * M_PI);
	y += 0.5;

	result.ColorAtPoint = _image->GetColor(result.ExtraInfoDouble * _image->Width(), y * _image->Height());
}
